package com.jxc.summer.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jxc.summer.dao.InOrderMapper;
import com.jxc.summer.dao.StorageMapper;
import com.jxc.summer.service.InOrderService;
import com.jxc.summer.util.UUIDUtil;

@Service
@Transactional
public class InOrderServiceImpl implements InOrderService {

	@Autowired
	private InOrderMapper inOrderMapper;
	@Autowired
	private StorageMapper storageMapper;
	@Override
	public boolean addin(Map<String, Object> params) {
		//添加订单
		params.put("to_inorout", 1);
		int result = inOrderMapper.addOrderIn(params);
		if(result<1){
			throw new RuntimeException();
		}
		List<Map<String,Object>> orderList = (List<Map<String, Object>>) params.get("orderList");
		for (Map<String, Object> map : orderList) {
			map.put("toi_companycode", params.get("to_companycode"));
			map.put("toi_orderitemid", UUIDUtil.get32UUID());
			//添加订单条目
			result = inOrderMapper.addOrderInItem(map);
			if(result<1){
				throw new RuntimeException();
			}
			//添加库存 如果单位是米则新增一条记录，如果单位是盘更新
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("ts_storageid", UUIDUtil.get32UUID());
			param.put("ts_cablemodel", MapUtils.getString(map, "toi_cablemodel"));
			param.put("ts_cablestandard", MapUtils.getString(map, "toi_cablestandard"));
			param.put("ts_unit", MapUtils.getString(map, "toi_unit"));
			param.put("ts_number", MapUtils.getString(map, "toi_number"));
			param.put("ts_quality", MapUtils.getString(map, "toi_quality"));
			param.put("ts_color", MapUtils.getString(map, "toi_color"));
			param.put("ts_customerid", MapUtils.getString(params, "to_customerid"));
			param.put("ts_storagetime", MapUtils.getObject(params, "to_ordertime"));
			param.put("ts_remark", "");
			param.put("ts_address", MapUtils.getObject(map, "toi_warehouse"));
			param.put("ts_companycode", MapUtils.getString(map, "toi_companycode"));
			if("米".equals(param.get("ts_unit"))){
				result = storageMapper.add(param);
				if(result<1){
					throw new RuntimeException();
				}
			}else{
				//查询库存中是否有相同的记录，如果有更新数量，如果没有新增
				List<Map<String, Object>> storageList = storageMapper.selectByOrder(param);
				if(storageList.size()>0){
					param.put("ts_storageid", MapUtils.getString(storageList.get(0),"ts_storageid"));
					param.put("ts_number", MapUtils.getFloatValue(storageList.get(0),"ts_number")+MapUtils.getFloatValue(param, "ts_number"));
					result = storageMapper.update(param);
					if(result<1){
						throw new RuntimeException();
					}
				}else{
					result = storageMapper.add(param);
					if(result<1){
						throw new RuntimeException();
					}
				}
			}
		}
		return true;
	}

}
